<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/9/10 0010
 * Time: 下午 4:26
 */
namespace app\api\controller;
use app\api\service\Pay as PayService;
use app\common\model\Userreceivetic;
use app\common\validate\requestPaymentValidate;
use app\lib\exception\ParameterException;
use think\Request;

class Pay extends Base{


    /**
     * 优惠券购买支付入口
     * @param Request $request
     * @return array|\think\response\Json
     */
    public function requestPayment(Request $request){
        (new requestPaymentValidate())->goCheck();
        $param = $request->param();
        if(!$this->checkuser($param['userId'])){
            return show(config('status.ERROR_STATUS'),'用户不存在','用户不存在');
        }
        //判断优惠券是否已经购买并且没有核销
        $check = $this->checkticket($param);
        if(!$check['pass']){
            if($check['status'] == 1000){
                return show(config('status.ERROR_STATUS'),'此优惠券已过期','此优惠券已过期');
            }elseif ($check['status'] == 2000){
                return show(config('status.ERROR_STATUS'),'您已经领取过此优惠券，并且还没核销','您已经领取过此优惠券，并且还没核销');
            }else{
                return show(config('status.ERROR_STATUS'),'此优惠券售罄','此优惠券售罄');
            }
        }
        $pay = new PayService($param);
        return $pay->pay();

    }


    private function checkuser($userId){
        $User = \app\common\model\User::get($userId);
        if($User){
            return true;
        }
        return false;
    }

    public function checkticket($param){
        $pass = [
            'status' => 1,
            'pass' => true
        ];
        $Ticket = \app\admin\model\Ticket::where(['id'=>$param['ticketId'],'status'=>5])->find();
        if(!$Ticket){
            throw new ParameterException([
                'msg' => '该活动不存在'
            ]);
        }else{
            if($Ticket->remainGross < 1){
                $pass['status'] = 3000;
                $pass['pass'] = false;
            }
        }

        if(date('Y-m-d H:i:s',time())>$Ticket->endTime){
            $pass['status'] = 1000;
            $pass['pass'] = false;
        }
        $Userreceivetic = Userreceivetic::where(['userId'=>$param['userId'],'ticketId'=>$param['ticketId'],'status'=>0])->find();
        if($Userreceivetic){
            $pass['status'] = 2000;
            $pass['pass'] = false;
        }
        return $pass;
    }

    //微信支付结果回调地址
    public function receiveNotify(){
        //通知频率为15/15/30/180/1800/1800/1800/1800/3600，单位：秒
        //1.检测库存量
        //2.更新订单状态
        //3.减库存
        //如果成功处理，则向微信返回成功处理的消息

        //特点：post；xml格式；不会携带参数

        $notify = new \app\api\service\WxNotify();
        $notify->Handle();

    }
}